package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.finer.erp.jeecg.bas.entity.ZrkCutting;
import io.finer.erp.jeecg.bas.entity.ZrkCuttingDetail;
import io.finer.erp.jeecg.bas.service.IZrkCuttingDetailService;
import io.finer.erp.jeecg.bas.service.IZrkCuttingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 智能分切
 * @Author: jeecg-boot
 * @Date:   2020-08-25
 * @Version: V1.0
 */
@Api(tags="智能分切")
@RestController
@RequestMapping("/bas/zrkCutting")
@Slf4j
public class ZrkCuttingController extends JeecgController<ZrkCutting, IZrkCuttingService> {

	@Autowired
	private IZrkCuttingService zrkCuttingService;

	@Autowired
	private IZrkCuttingDetailService zrkCuttingDetailService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param zrkCutting
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "智能分切-分页列表查询")
	@ApiOperation(value="智能分切-分页列表查询", notes="智能分切-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkCutting zrkCutting,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkCutting> queryWrapper = QueryGenerator.initQueryWrapper(zrkCutting, req.getParameterMap());
		Page<ZrkCutting> page = new Page<ZrkCutting>(pageNo, pageSize);
		IPage<ZrkCutting> pageList = zrkCuttingService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
     *   添加
     * @param zrkCutting
     * @return
     */
    /**
     * @Description 
     * @param zrkCutting
     * @return
     * Create at: 2020-09-04 10:38:42
     * @author: duanyong
     * Revision:
     *    2020-09-04 10:38:42 - first revision by duanyong
     *        
     */
    /**
     * @Description 
     * @param zrkCutting
     * @return
     * Create at: 2020-09-04 10:38:43
     * @author: duanyong
     * Revision:
     *    2020-09-04 10:38:43 - first revision by duanyong
     *        
     */
    @AutoLog(value = "智能分切-添加")
    @ApiOperation(value="智能分切-添加", notes="智能分切-添加")
    @PostMapping(value = "/add")
    public Result<?> add(  ZrkCutting zrkCutting) {
    	this.zrkCuttingService.createCutting(zrkCutting);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑
     * @param zrkCutting
     * @return
     */
    @AutoLog(value = "智能分切-编辑")
    @ApiOperation(value="智能分切-编辑", notes="智能分切-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ZrkCutting zrkCutting) {
        zrkCuttingService.updateById(zrkCutting);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "智能分切-通过id删除")
    @ApiOperation(value="智能分切-通过id删除", notes="智能分切-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        zrkCuttingService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "智能分切-批量删除")
    @ApiOperation(value="智能分切-批量删除", notes="智能分切-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.zrkCuttingService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZrkCutting zrkCutting) {
        return super.exportXls(request, zrkCutting, ZrkCutting.class, "智能分切");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZrkCutting.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-智能分切方案记录-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "智能分切方案记录-通过主表ID查询")
	@ApiOperation(value="智能分切方案记录-通过主表ID查询", notes="智能分切方案记录-通过主表ID查询")
	@GetMapping(value = "/listZrkCuttingDetailByMainId")
    public Result<?> listZrkCuttingDetailByMainId(ZrkCuttingDetail zrkCuttingDetail,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<ZrkCuttingDetail> queryWrapper = QueryGenerator.initQueryWrapper(zrkCuttingDetail, req.getParameterMap());
        Page<ZrkCuttingDetail> page = new Page<ZrkCuttingDetail>(pageNo, pageSize);
        IPage<ZrkCuttingDetail> pageList = zrkCuttingDetailService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

	/**
	 * 添加
	 * @param zrkCuttingDetail
	 * @return
	 */
	@AutoLog(value = "智能分切方案记录-添加")
	@ApiOperation(value="智能分切方案记录-添加", notes="智能分切方案记录-添加")
	@PostMapping(value = "/addZrkCuttingDetail")
	public Result<?> addZrkCuttingDetail(@RequestBody ZrkCuttingDetail zrkCuttingDetail) {
		zrkCuttingDetailService.save(zrkCuttingDetail);
		return Result.ok("添加成功！");
	}

    /**
	 * 编辑
	 * @param zrkCuttingDetail
	 * @return
	 */
	@AutoLog(value = "智能分切方案记录-编辑")
	@ApiOperation(value="智能分切方案记录-编辑", notes="智能分切方案记录-编辑")
	@PutMapping(value = "/editZrkCuttingDetail")
	public Result<?> editZrkCuttingDetail(@RequestBody ZrkCuttingDetail zrkCuttingDetail) {
		zrkCuttingDetailService.updateById(zrkCuttingDetail);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "智能分切方案记录-通过id删除")
	@ApiOperation(value="智能分切方案记录-通过id删除", notes="智能分切方案记录-通过id删除")
	@DeleteMapping(value = "/deleteZrkCuttingDetail")
	public Result<?> deleteZrkCuttingDetail(@RequestParam(name="id",required=true) String id) {
		zrkCuttingDetailService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "智能分切方案记录-批量删除")
	@ApiOperation(value="智能分切方案记录-批量删除", notes="智能分切方案记录-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkCuttingDetail")
	public Result<?> deleteBatchZrkCuttingDetail(@RequestParam(name="ids",required=true) String ids) {
	    this.zrkCuttingDetailService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportZrkCuttingDetail")
    public ModelAndView exportZrkCuttingDetail(HttpServletRequest request, ZrkCuttingDetail zrkCuttingDetail) {
		 // Step.1 组装查询条件
		 QueryWrapper<ZrkCuttingDetail> queryWrapper = QueryGenerator.initQueryWrapper(zrkCuttingDetail, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<ZrkCuttingDetail> pageList = zrkCuttingDetailService.list(queryWrapper);
		 List<ZrkCuttingDetail> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "智能分切方案记录"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, ZrkCuttingDetail.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("智能分切方案记录报表", "导出人:" + sysUser.getRealname(), "智能分切方案记录"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importZrkCuttingDetail/{mainId}")
    public Result<?> importZrkCuttingDetail(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<ZrkCuttingDetail> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkCuttingDetail.class, params);
				 for (ZrkCuttingDetail temp : list) {
                    temp.setZrkCuttingId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 zrkCuttingDetailService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-智能分切方案记录-end----------------------------------------------*/


    /**
     * @Description 选择分切方案
     * @param planName
     * @param zrkCuttingId
     * @return
     * Create at: 2020-08-27 18:04:04
     * @author: duanyong
     * Revision:
     *    2020-08-27 18:04:04 - first revision by duanyong
     *        
     */
    @RequestMapping("/choosePlan")
    public Result<?> choosePlan(@RequestParam(name="planName", required=true) String planName
    		, @RequestParam(name="zrkCuttingId", required=true) String zrkCuttingId){
    	Result<Object> result = new Result<>();
    	LambdaUpdateWrapper<ZrkCuttingDetail> update = new LambdaUpdateWrapper<>();
    	update.eq(ZrkCuttingDetail::getZrkCuttingId, zrkCuttingId);
    	update.eq(ZrkCuttingDetail::getMethodName, planName);
    	update.set(ZrkCuttingDetail::getIsSelected, "1");
    	this.zrkCuttingDetailService.update(update);
    	
    	return result.success("选择完成");
    }
}
